package com.lvtulife.common.web.util;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

public class JdomXML {
    private static Logger logger = LoggerFactory.getLogger(JdomXML.class);
    private Document doc;
    private Map propertyCache = new HashMap();

    public JdomXML(String path) {
        try {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl == null) {
                cl = JdomXML.class.getClassLoader();
            }

            URL url = cl.getResource(path);

            if (logger.isDebugEnabled()) {
                logger.debug("配置文件路径：" + url.getFile());
            }

            SAXBuilder builder = new SAXBuilder();
            this.doc = builder.build(url);
        } catch (Exception e) {
            logger.error("配置文件解析错误：\r\n" + e);
        }
    }

    public String getProperty(String name) {
        if (this.propertyCache.containsKey(name)) {
            return ((String) this.propertyCache.get(name));
        }

        String[] propName = parsePropertyName(name);

        Element element = this.doc.getRootElement();
        for (int i = 0; i < propName.length; ++i) {
            element = element.getChild(propName[i]);
            if (element == null) {
                return null;
            }

        }

        String value = element.getText();
        if ("".equals(value)) {
            return null;
        }

        value = value.trim();
        this.propertyCache.put(name, value);
        return value;
    }

    public String[] getChildrenProperties(String parent) {
        String[] propName = parsePropertyName(parent);

        Element element = this.doc.getRootElement();

        for (int i = 0; i < propName.length; ++i) {
            System.out.println(propName);
            element = element.getChild(propName[i]);
            if (element == null) {
                return new String[0];
            }
        }

        List children = element.getChildren();
        int childCount = children.size();
        String[] childrenNames = new String[childCount];
        for (int i = 0; i < childCount; ++i) {
            childrenNames[i] = ((Element) children.get(i)).getName();
        }
        return childrenNames;
    }

    public String[] getChildrenPropertyValues(String parent) {
        String[] propName = parsePropertyName(parent);

        Element element = this.doc.getRootElement();
        for (int i = 0; i < propName.length; ++i) {
            element = element.getChild(propName[i]);
            if (element == null) {
                return new String[0];
            }
        }

        List children = element.getChildren();
        int childCount = children.size();
        String[] childrenValue = new String[childCount];
        for (int i = 0; i < childCount; ++i) {
            childrenValue[i] = ((Element) children.get(i)).getText();
        }
        return childrenValue;
    }

    public void setProperty(String name, String value) {
        this.propertyCache.put(name, value);

        String[] propName = parsePropertyName(name);

        Element element = this.doc.getRootElement();
        for (int i = 0; i < propName.length; ++i) {
            if (element.getChild(propName[i]) == null) {
                element.addContent(new Element(propName[i]));
            }
            element = element.getChild(propName[i]);
        }

        element.setText(value);

        saveProperties();
    }

    public void deleteProperty(String name) {
        String[] propName = parsePropertyName(name);

        Element element = this.doc.getRootElement();
        for (int i = 0; i < propName.length - 1; ++i) {
            element = element.getChild(propName[i]);

            if (element == null) {
                return;
            }
        }

        element.removeChild(propName[(propName.length - 1)]);

        saveProperties();
    }

    public synchronized void saveProperties() {
    }

    private String[] parsePropertyName(String name) {
        int size = 1;
        for (int i = 0; i < name.length(); ++i) {
            if (name.charAt(i) != '.')
                continue;
            ++size;
        }

        String[] propName = new String[size];

        StringTokenizer tokenizer = new StringTokenizer(name, ".");
        int i = 0;
        while (tokenizer.hasMoreTokens()) {
            propName[i] = tokenizer.nextToken();
            ++i;
        }
        return propName;
    }
}

